package com.example.pv.handlermessageprogress;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {

    ProgressBar bar =null;
    Button button =null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bar = (ProgressBar)findViewById(R.id.progressBar6);
        button =(Button)findViewById(R.id.button);
        button.setOnClickListener(new ButtonListener());
    }
    class ButtonListener implements OnClickListener{
        public void onClick(View view){
            bar.setVisibility(View.VISIBLE);
            updateBarHandler.post(updateThread);
        }
    };

    Handler updateBarHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            bar.setProgress(msg.arg1);
            updateBarHandler.post(updateThread);
        }
    };

    Runnable updateThread =new Runnable() {
        int i=0;
        @Override
        public void run() {

            if (i <= 90) {
                System.out.println("Begin");
                i = i + 10;
                Message message = updateBarHandler.obtainMessage();
                message.arg1 = i;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                updateBarHandler.sendMessage(message);
            }

            else  {
                updateBarHandler.removeCallbacks(updateThread);
                bar.setVisibility(View.GONE);
                i=0;
            }

        }
    };
}
